package com.topisv.tms.web.work.ExceptionOrder;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.ExceptionOrder.ExceptionOrder;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.BackupTaskOrdenoService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.service.work.ExceptionOrder.ExceptionOrderService;

import net.sf.json.JSONObject;

/**
 * 取消单管理—control
 * @author ch
 *
 */
@Controller
@RequestMapping(value = "/cancelOrder")
public class CancelOrderController {

	private static final Logger logger = LoggerFactory.getLogger(CancelOrderController.class);
	private static final int PAGE_SIZE = 20;
	
	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private EdiOrderService ediOrderService;
	@Autowired
	private ExceptionOrderService exceptionOrderService;
	@Autowired
	private BackupTaskOrdenoService backupTaskOrdenoService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private WorkTaskService workTaskService;

	
	/**
	 * 导向异常单管理页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toCancelOrderMgr")
	public String toCancelOrderMgr(@RequestParam(value = "page", defaultValue = "1") int pageNumber,Model model, ServletRequest request) {
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			
			//如果是paiu用户,初始化数据
			if("paiu".equals(curUser.userType)){
				//取消订单
			    Map<String, Object> param=new HashMap<String, Object>();
			    param.put("customerCodes", StringUtils.isBlank(curUser.customers)?"blank":curUser.customers);
			    param.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
			    param.put("exceptionType", "cancel");
			    Page<ExceptionOrder> page = this.exceptionOrderService.loadPageByParam(param,pageNumber, PAGE_SIZE);
				model.addAttribute("page", page);
			}
		    
		    //如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				String customerCode=customerList.get(0).getCustomerCode();
				model.addAttribute("_customerCode",customerCode);
				
				//初始化仓库数据
				List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
				
				//取消订单
			    Map<String, Object> param=new HashMap<String, Object>();
			    param.put("customerCodes", customerCode);
			    param.put("exceptionType", "cancel");
			    Page<ExceptionOrder> page = this.exceptionOrderService.loadPageByParam(param,pageNumber, PAGE_SIZE);
				model.addAttribute("page", page);
			}
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/exceptionOrder/cancelOrderMgr";
	}
	
	
	/**
	 * 查询取消单
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryCancelOrder")
	public String queryCancelOrder(@RequestParam(value = "page", defaultValue = "1") int pageNumber,Model model, ServletRequest request) {
		try {
			
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//查询结果
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			String customerCode=(String) param.get("customerCode");
			String warehouseCode=(String) param.get("warehouseCode");
			
			if(StringUtils.isBlank(customerCode)){
				param.put("customerCodes", this.customersService.loadCustomerByAuthority(curUser.jobuuid));
			}else{
				param.put("customerCodes", customerCode);
			}
			
			if(StringUtils.isBlank(warehouseCode)){
				param.put("areagroups", curUser.areagroups);
			}else{
				param.put("areagroups", warehouseCode);
			}
			
			Date fromDate=null;
			Date toDate=null;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			if(StringUtils.isNotEmpty(fromDateStr)){
				fromDate=sdf.parse(fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
				toDate=sdf.parse(toDateStr+" 23:59:59");
				
			}
			param.put("fromDate1", fromDate);
			param.put("toDate1", toDate);
			param.put("exceptionType", "cancel");
			
			Page<ExceptionOrder> page = this.exceptionOrderService.loadPageByParam(param,pageNumber, PAGE_SIZE);
			model.addAttribute("page", page);
			model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(param, "_"));
			
			//初始化仓库数据
			if(StringUtils.isNotBlank(customerCode)){
				List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
			}
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/exceptionOrder/cancelOrderMgr";
	}
	
	/**
	 * 导向登记取消单页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toCancelOrderPage")
	public String toCancelOrderPage(Model model, ServletRequest request) {
		try {
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "work/exceptionOrder/cancelOrderRegist";
	}
	
	
	/**
	 * 查询取消单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxQueryCancelOrder")
	public void ajaxQueryCancelOrder(ServletRequest request,HttpServletResponse response) {
		
		PrintWriter out=null;
		JSONObject json=null;
		
		try {	
			out = response.getWriter();
			json = new JSONObject();
			String orderno=request.getParameter("orderno"); 
			
			EdiOrder ediOrder=this.ediOrderService.findByOrdernoOrCustomerorderno(orderno);
			if(ediOrder==null){ //不存在此订单
	    		json.put("msg", "noExist");
	    	}else{
	    		
	    		Customers customer = customersService.findByCustomerCode(ediOrder.getCustomerCode());
	    		if("1".equals(customer.getOpenQm())){
	    			json.put("msg", "qmNotCreate");
	    		}else {
		    		String cancelStatus=ediOrder.getOrderStatus();
		    		if("cancel".equals(cancelStatus)){
						json.put("msg", "cancel");  //已取消
					}else if("recall".equals(cancelStatus)){
						json.put("msg", "recall");  //已取消重发
					}
	    		}
	    		WorkOrder workOrder=this.workOrderService.loadByAnyOrderno(orderno);
	    		if(workOrder==null){  //未生成作业批次
	    			json.put("ediOrder", ediOrder);
	    			json.put("flag", "false");
	 		    }else{  //已生成作业批次
	 		    	
 			    	String status=workOrder.getStatus();
 					if("6".equals(status) || "7".equals(status) || "8".equals(status)){ //已经发货
 						json.put("msg", "sended");  //已发货
 					}
 					json.put("ediOrder", ediOrder);
	 		    	json.put("workOrder", workOrder);
	 		    	json.put("flag", "true");
	 		    	
	 		    }
	    	}
			out.print(json);
		} catch (Exception e) {
			
			logger.error("error",e);
			json.put("msg", "error");
			out.print(json);
		}
	}

	
	/**
	 * 取消订单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCancelOrder")
	public void ajaxCancelOrder(ServletRequest request,HttpServletResponse response) {
		
		PrintWriter out=null;
		JSONObject json=null;
		String msg=null;
		
		try {	
			out = response.getWriter();
			json = new JSONObject();
			
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			String orderno=request.getParameter("orderno"); 
			EdiOrder ediOrder=this.ediOrderService.findByOrdernoOrCustomerorderno(orderno);
			if("JF".equals(ediOrder.getMessage())){//集发取消逻辑
				backupTaskOrdenoService.cancelOrdeno(orderno, ediOrder.getCustomerCode(), curUser.jobuuid);
			}else{//商发取消逻辑
				msg=this.workOrderService.cancelOrder(orderno,curUser.jobuuid);
			}
			
		    json.put("msg", msg);
			out.print(json);
			
		} catch (Exception e) {
			
			logger.error("error",e);
			json.put("msg", "error");
			out.print(json);
		}
	}
	
	/**
	 * 重发取消单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxRecall")
	public void ajaxRecall(ServletRequest request,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		String msg=null;
		
		try {	
			out = response.getWriter();
			json = new JSONObject();
			
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			String orderno=request.getParameter("orderno"); 
			msg=this.workOrderService.recallOrder(orderno,curUser.jobuuid);
			
		    json.put("msg", msg);
			out.print(json);
			
		} catch (Exception e) {
			
			logger.error("error",e);
			json.put("msg", "error");
			out.print(json);
		}
	}
	
	/**
	 * 拦截标识
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCancelFlag")
	public void ajaxCancelFlag(ServletRequest request,HttpServletResponse response) {
		
		PrintWriter out=null;
		JSONObject json=null;
		String msg=null;
		
		//bug531 by zhangweize
		boolean isLockSuccess = false;
		String orderno=request.getParameter("orderno");
		String flag=request.getParameter("flag");
		
		try {	
			out = response.getWriter();
			json = new JSONObject();
			
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			
			// 根据商家、仓库进行加锁操作 bug531 by zhangweize
			isLockSuccess = workTaskService.lock("ajaxCancelFlag", orderno, "-");
			if (!isLockSuccess) {
				json.put("msg", "exceptionError");
				json.put("content", "当前商家以及所属的仓库已在处理,请勿重复处理！");
				return;
			}
			
			msg=this.exceptionOrderService.cancelFlag(orderno,curUser.jobuuid,flag);
			
		    json.put("msg", msg);
			
		} catch (Exception e) {
			
			json.put("msg", "exceptionError");
			json.put("content", e.getMessage());
			
		} finally {
			
			//bug531 by zhangweize
			if(isLockSuccess){
				workTaskService.releaseLock("ajaxCancelFlag", orderno);
			}
			out.print(json);
		}
	}
	
}
